package cn.rkylin.oms.item.adapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.rkylin.oms.common.base.AbstractAdapterFactory;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.ItemsInventoryGetRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.request.ItemsSellerListGetRequest;
import com.taobao.api.response.ItemsInventoryGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taobao.api.response.ItemsSellerListGetResponse;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.core.IDataBaseFactory;
import cn.rkylin.core.utils.SnoGerUtil;
import cn.rkylin.core.utils.StringUtil;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.DateUtil;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.common.utils.SkuUtil;
import cn.rkylin.oms.item.dao.IItemDAO;
import cn.rkylin.oms.item.domain.Item;
import cn.rkylin.oms.item.domain.Sku;
import cn.rkylin.oms.item.domain.taobao.TopItem;
import cn.rkylin.oms.item.domain.taobao.TopSku;
import cn.rkylin.oms.item.request.PushItemDeListing;
import cn.rkylin.oms.item.request.PushItemListing;
import cn.rkylin.oms.item.request.PushItemQuantityUpdate;
import cn.rkylin.oms.item.vo.ItemVO;

/**
 * 淘宝商品代理
 *
 * @author jipengcheng
 * @version 1.0
 * @created 2017.02.13
 */
@Service("taoBaoItemVisitor")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class TaoBaoItemVisitor extends ItemVisitor {

    private static final Log logger = LogFactory.getLog(TaoBaoItemVisitor.class);
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private IDataBaseFactory dao;
    @Autowired
    private IItemDAO itemDAO;
    @Autowired
    LogUtil logUtil;

    /**
     * 每页行数
     */
    private static final Long pageSize = 20L;
    /**
     * 淘宝商品
     */
    private List<TopItem> topItemList = new ArrayList<TopItem>();

    /**
     * OMS调用地址
     */
    @Value("${oms.address}")
    private String omsUrl;

    /**
     * 构造函数
     */
    public TaoBaoItemVisitor() {

    }

    /**
     * 按商品编码获取商品
     *
     * @param shopId
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public List<Item> getItemListByItemCode(String shopId, Map<String, Object> paramMap) throws Exception {
        try {
            if (paramMap == null) {
                return null;
            }

            if (shopVO == null) {
                return null;
            }

            String strNumiids = paramMap.get("itemCode").toString();
            getItemByNumiids(strNumiids);
            return topItemList2ItemList(shopId);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 按修改时间获取商品
     *
     * @param shopId
     * @return List<Item>
     * @throws Exception
     */
    @Override
    public List<Item> getItemListByModifyTime(String shopId, Map<String, Object> paramMap) throws Exception {
        if (paramMap == null) {
            return null;
        }

        if (shopVO == null) {
            return null;
        }

        Calendar startTime = Calendar.getInstance();
        startTime.setTime(simpleDateFormat.parse(paramMap.get("startTime").toString()));
        Calendar endTime = Calendar.getInstance();
        endTime.setTime(simpleDateFormat.parse(paramMap.get("endTime").toString()));

        logger.debug(paramMap.get("startTime").toString() + "---" + paramMap.get("endTime").toString());

        getInventoryItem(startTime, endTime);
        getOnSaleItem(startTime, endTime);
        return topItemList2ItemList(shopId);
    }

    /**
     * 下载平台商品
     *
     * @param shopId
     * @return List<Item>
     * @throws Exception
     */
    @Override
    public List<Item> getItemListAll(String shopId) throws Exception {
        try {

            if (shopVO == null) {
                return null;
            }

            // 获取在库商品
            getInventoryItem();
            // 获取在售商品
            getOnSaleItem();
            return topItemList2ItemList(shopId);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 把淘宝商品(TopItem)转换成OMS平台商品(Item)
     *
     * @param shopId
     * @return
     */
    private List<Item> topItemList2ItemList(String shopId) {
        List<Item> returnList = new ArrayList<Item>();
        // 根据ShopId获取Shop相关信息
        for (TopItem topItem : topItemList) {
            // 添加ITEM数据
            Item item = new Item();
            // item.setEcItemId(SnoGerUtil.getUUID());
            item.setEcItemCode(topItem.getNumIid().toString());
            item.setEcItemName(topItem.getTitle());
            item.setOuterCode(topItem.getOuterId());
            item.setPrjId(shopVO.getPrjId());
            item.setShopId(shopId);
            item.setShopName(shopVO.getShopName());
            item.setShopAccount(shopVO.getShopAccount());
            item.setShopType(shopVO.getShopType());
            // item.setItemUrl("");
            item.setSalePrice(topItem.getPrice());
            item.setPostFee(topItem.getPostFee());
            item.setEmsPostFee(topItem.getEmsFee());
            item.setLgstPostFee(topItem.getExpressFee());
            // item.setRemark("");
            item.setApproveStatus(topItem.getApproveStatus().equals("onsale") ? "上架" : "下架");
            item.setListTime(topItem.getListTime());
            // item.setAutoList("n");
            item.setDelistTime(topItem.getDelistTime());
            // item.setAutoDelist("n");

            // 如果商品包含sku信息
            if (topItem.getTopSkuList() != null && topItem.getTopSkuList().size() > 0) {
                for (TopSku topSku : topItem.getTopSkuList()) {

                    // 添加SKU数据
                    Sku sku = new Sku();
                    // sku.setEcSkuId(SnoGerUtil.getUUID());
                    sku.setShopId(shopId);
                    sku.setEcItemId(item.getEcItemId());
                    sku.setEcItemCode(item.getEcItemCode());
                    sku.setEcSkuCode(topSku.getSkuId().toString());
                    sku.setEcSkuName(SkuUtil.getEcSkuName(topSku.getPropertiesName()));
                    sku.setOuterCode(topSku.getOuterId());
                    sku.setSalePrice(topSku.getPrice());
                    // sku.setWeight(new BigDecimal(0.00));
                    sku.setQty(topSku.getQuantity());
                    // sku.setPostFee(new BigDecimal(0.00));
                    // sku.setAutoStock("n");
                    item.getSkuList().add(sku);
                }
            } else {
                // 添加SKU数据, 此时SkuId = 0
                Sku sku = new Sku();
                // sku.setEcSkuId(SnoGerUtil.getUUID());
                sku.setShopId(shopId);
                sku.setEcItemId(item.getEcItemId());
                sku.setEcItemCode(item.getEcItemCode());
                sku.setEcSkuCode("0");
                sku.setEcSkuName(topItem.getTitle());
                sku.setOuterCode(topItem.getOuterId());
                sku.setSalePrice(topItem.getPrice());
                // sku.setWeight(new BigDecimal(0.00));
                sku.setQty(topItem.getNum());
                // sku.setPostFee(new BigDecimal(0.00));
                // sku.setAutoStock("n");
                item.getSkuList().add(sku);
            }
            returnList.add(item);
        }
        return returnList;
    }

    /**
     * 获取当前会话用户库存中的商品列表(全部)
     *
     * @return 1成功，0失败
     */
    private int getInventoryItem() throws Exception {

        Calendar startModified = Calendar.getInstance();
        startModified.add(Calendar.YEAR, -2);
        Calendar endModified = Calendar.getInstance();

        return getInventoryItem(startModified, endModified);
    }

    /**
     * 获取当前会话用户库存中的商品列表(按时间段筛选)
     *
     * @param startModify 起始的修改时间
     * @param endModify   结束的修改时间
     * @return 1成功，0失败
     */
    private int getInventoryItem(Calendar startModified, Calendar endModified) throws Exception {

        int day = 15;
        Calendar startTime = Calendar.getInstance();
        startTime.setTime(startModified.getTime());
        Calendar endTime = Calendar.getInstance();
        endTime.setTime(startModified.getTime());
        endTime.add(Calendar.DATE, day);

        while (endTime.getTimeInMillis() < endModified.getTimeInMillis()) {
            getInventoryItem(startTime, endTime, "for_shelved");
            getInventoryItem(startTime, endTime, "sold_out");
            getInventoryItem(startTime, endTime, "violation_off_shelf");

            startTime.setTime(endTime.getTime());
            endTime.add(Calendar.DATE, day);
        }

        // 最后一次获取
        getInventoryItem(startTime, endTime, "for_shelved");
        getInventoryItem(startTime, endTime, "sold_out");
        getInventoryItem(startTime, endTime, "violation_off_shelf");
        return 1;

    }

    /**
     * 获取当前会话用户库存中的商品列表(按时间段筛选)
     *
     * @param startModify 起始的修改时间
     * @param endModify   结束的修改时间
     * @param banner      分类字段。可选值: regular_shelved(定时上架) never_on_shelf(从未上架)
     *                    sold_out(全部卖完) off_shelf(我下架的) for_shelved(等待所有上架)
     *                    violation_off_shelf(违规下架的) 默认查询的是for_shelved(等待所有上架)这个状态的商品
     * @return 1成功，0失败
     * @throws ApiException
     */
    private int getInventoryItem(Calendar startModified, Calendar endModified, String banner) throws Exception {

        // taobao.items.inventory.get
        TaobaoClient client = new DefaultTaobaoClient(shopVO.getApiUrl(), shopVO.getAppKey(), shopVO.getAppSecret());
        ItemsInventoryGetRequest req = new ItemsInventoryGetRequest();
        req.setFields("num_iid");
        req.setPageSize(pageSize);
        req.setStartModified(startModified.getTime());
        req.setEndModified(endModified.getTime());
        req.setBanner(banner);
        req.setPageNo(1L);

        ItemsInventoryGetResponse rsp = client.execute(req, shopVO.getSessionKey());

        if (!rsp.isSuccess()) {
            return 0;
        }
        if (rsp.getItems() == null || rsp.getItems().size() < 1) {
            return 1;
        }

        long totalPageNo = rsp.getTotalResults() % pageSize > 0 ? rsp.getTotalResults() / pageSize + 1
                : rsp.getTotalResults() / pageSize;

        if (totalPageNo >= 1) {
            for (long pageNo = totalPageNo; pageNo >= 1; pageNo--) {
                getInventoryItem(startModified, endModified, pageNo, banner);
            }
        }
        return 1;
    }

    /**
     * 获取当前会话用户库存中的商品列表(按时间段筛选)
     *
     * @param startModified 起始的修改时间
     * @param endModified   结束的修改时间
     * @param pageNo        页码
     * @param banner        分类字段。可选值: regular_shelved(定时上架) never_on_shelf(从未上架)
     *                      sold_out(全部卖完) off_shelf(我下架的) for_shelved(等待所有上架)
     *                      violation_off_shelf(违规下架的) 默认查询的是for_shelved(等待所有上架)这个状态的商品
     * @return
     * @throws Exception
     */
    private int getInventoryItem(Calendar startModified, Calendar endModified, long pageNo, String banner) throws Exception {

        // taobao.items.inventory.get
        TaobaoClient client = new DefaultTaobaoClient(shopVO.getApiUrl(), shopVO.getAppKey(), shopVO.getAppSecret());
        ItemsInventoryGetRequest req = new ItemsInventoryGetRequest();
        req.setFields("num_iid");
        req.setPageSize(pageSize);
        req.setStartModified(startModified.getTime());
        req.setEndModified(endModified.getTime());
        req.setBanner(banner);
        req.setPageNo(pageNo);

        ItemsInventoryGetResponse rsp = client.execute(req, shopVO.getSessionKey());
        if (!rsp.isSuccess()) {
            return 0;
        }
        if (rsp.getItems() == null || rsp.getItems().size() < 1) {
            return 1;
        }

        String strNumiid = "";
        for (com.taobao.api.domain.Item item : rsp.getItems()) {
            // 获取商品字符串
            if (strNumiid.indexOf(item.getNumIid() + ",") < 0) {
                strNumiid += item.getNumIid() + ",";
            }
        }

        // 获取商品字符串
        if (strNumiid.length() > 0) {
            strNumiid = strNumiid.substring(0, strNumiid.length() - 1);
        }

        // 获取商品
        getItemByNumiids(strNumiid);

        return 1;
    }

    /**
     * 获取当前用户作为卖家的出售中的商品列表(全部)
     *
     * @return 1成功，0失败
     * @throws Exception
     */
    private int getOnSaleItem() throws Exception {

        // taobao.items.onsale.get
        TaobaoClient client = new DefaultTaobaoClient(shopVO.getApiUrl(), shopVO.getAppKey(), shopVO.getAppSecret());
        ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
        req.setFields("num_iid");
        req.setPageSize(pageSize);
        req.setPageNo(1L);
        ItemsOnsaleGetResponse rsp = client.execute(req, shopVO.getSessionKey());

        // 请求失败
        if (!rsp.isSuccess()) {
            return 0;
        }
        if (rsp.getItems() == null || rsp.getItems().size() < 1) {
            return 1;
        }

        // 获取最大页码
        long totalPageNo = rsp.getTotalResults() % pageSize > 0 ? rsp.getTotalResults() / pageSize + 1
                : rsp.getTotalResults() / pageSize;

        // 分页获取商品
        if (totalPageNo >= 1) {
            for (long pageNo = totalPageNo; pageNo >= 1; pageNo--) {
                getOnSaleItemByPageNo(pageNo);
            }
        }
        return 1;
    }

    /**
     * 获取当前用户作为卖家的出售中的商品列表(修改时间)
     *
     * @param startModified 修改开始时间
     * @param endModified   修改结束时间
     * @return 1成功，0失败
     */
    private int getOnSaleItem(Calendar startModified, Calendar endModified) throws Exception {

        // taobao.items.onsale.get
        TaobaoClient client = new DefaultTaobaoClient(shopVO.getApiUrl(), shopVO.getAppKey(), shopVO.getAppSecret());
        ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
        req.setFields("num_iid");
        req.setStartModified(startModified.getTime());
        req.setEndModified(endModified.getTime());
        req.setPageSize(pageSize);
        req.setPageNo(1L);
        ItemsOnsaleGetResponse rsp = client.execute(req, shopVO.getSessionKey());

        // 请求失败
        if (!rsp.isSuccess()) {
            return 0;
        }
        if (rsp.getItems() == null || rsp.getItems().size() < 1) {
            return 1;
        }

        // 获取最大页码
        long totalPageNo = rsp.getTotalResults() % pageSize > 0 ? rsp.getTotalResults() / pageSize + 1
                : rsp.getTotalResults() / pageSize;

        // 分页获取商品
        if (totalPageNo >= 1) {
            for (long pageNo = totalPageNo; pageNo >= 1; pageNo--) {
                getOnSaleItem(startModified, endModified, pageNo);
            }
        }

        return 1;
    }

    /**
     * 获取当前用户作为卖家的出售中的商品列表(修改时间)
     *
     * @param startModified 修改开始时间
     * @param endModified   修改结束时间
     * @param pageNo        页码
     * @return 1成功，0失败
     * @throws Exception
     */
    private int getOnSaleItem(Calendar startModified, Calendar endModified, long pageNo) throws Exception {

        // taobao.items.onsale.get
        TaobaoClient client = new DefaultTaobaoClient(shopVO.getApiUrl(), shopVO.getAppKey(), shopVO.getAppSecret());
        ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
        req.setFields("num_iid");
        req.setStartModified(startModified.getTime());
        req.setEndModified(endModified.getTime());
        req.setPageSize(pageSize);
        req.setPageNo(pageNo);
        ItemsOnsaleGetResponse rsp = client.execute(req, shopVO.getSessionKey());
        // 请求失败
        if (!rsp.isSuccess()) {
            return 0;
        }
        if (rsp.getItems() == null || rsp.getItems().size() < 1) {
            return 1;
        }

        String strNumiid = "";
        for (com.taobao.api.domain.Item item : rsp.getItems()) {
            // 获取商品字符串
            if (strNumiid.indexOf(item.getNumIid() + ",") < 0) {
                strNumiid += item.getNumIid() + ",";
            }
        }
        // 获取商品字符串
        if (strNumiid.length() > 0) {
            strNumiid = strNumiid.substring(0, strNumiid.length() - 1);
        }

        // 获取商品
        getItemByNumiids(strNumiid);
        return 1;
    }

    /**
     * 获取当前用户作为卖家的出售中的商品列表(全部)
     *
     * @param pageNo 页码
     * @return 1成功，0失败
     * @throws Exception
     */
    private int getOnSaleItemByPageNo(long pageNo) throws Exception {

        // taobao.items.onsale.get
        TaobaoClient client = new DefaultTaobaoClient(shopVO.getApiUrl(), shopVO.getAppKey(), shopVO.getAppSecret());
        ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
        req.setFields("num_iid");
        req.setPageSize(pageSize);
        req.setPageNo(pageNo);

        ItemsOnsaleGetResponse rsp = client.execute(req, shopVO.getSessionKey());

        if (!rsp.isSuccess()) {
            return 0;
        }
        if (rsp.getItems() == null || rsp.getItems().size() < 1) {
            return 1;
        }

        String strNumiid = "";
        for (com.taobao.api.domain.Item item : rsp.getItems()) {
            // 获取商品字符串
            if (strNumiid.indexOf(item.getNumIid() + ",") < 0) {
                strNumiid += item.getNumIid() + ",";
            }
        }
        // 获取商品字符串
        if (strNumiid.length() > 0) {
            strNumiid = strNumiid.substring(0, strNumiid.length() - 1);
        }

        // 获取商品
        getItemByNumiids(strNumiid);
        return 1;
    }

    /**
     * 批量获取商品信息(支持单个和批量,实现了分页)
     *
     * @param strNumiid 商品数字id拼凑
     * @return
     * @throws Exception
     */
    private int getItemByNumiids(String strNumiid) throws Exception {
        if (strNumiid == null || strNumiid.length() <= 0)
            return 1;

        int rowCount = 0;
        String tempNumiid = "";

        String[] numiidList = strNumiid.split(",");
        for (String numiid : numiidList) {
            rowCount++;
            tempNumiid += numiid + ",";

            if (rowCount == pageSize) {
                tempNumiid = tempNumiid.substring(0, tempNumiid.length() - 1);
                getApiItemByNumiids(tempNumiid);

                tempNumiid = "";
                rowCount = 0;
            }
        }

        if (rowCount != 0) {
            tempNumiid = tempNumiid.substring(0, tempNumiid.length() - 1);
            getApiItemByNumiids(tempNumiid);
        }
        return 1;
    }

    /**
     * 批量获取商品信息
     *
     * @param strNumiid 商品数字id拼凑
     * @param getMode   1成功，0失败
     * @throws Exception
     */
    private int getApiItemByNumiids(String strNumiid) throws Exception {

        if (StringUtils.isBlank(strNumiid)) {
            return 1;
        }

        // taobao.items.seller.list.get
        TaobaoClient client = new DefaultTaobaoClient(shopVO.getApiUrl(), shopVO.getAppKey(), shopVO.getAppSecret());
        ItemsSellerListGetRequest req = new ItemsSellerListGetRequest();
        req.setFields("iid,detail_url,num_iid,title,nick,type,cid,seller_cids,props,"
                + "input_pids,desc,input_str,pic_url,num,valid_thru,list_time,"
                + "delist_time,stuff_status,price,post_fee,express_fee,ems_fee,has_discount,"
                + "freight_payer,has_invoice,has_warranty,has_showcase,modified,"
                + "increment,approve_status,postage_id,product_id,auction_point,"
                + "property_alias,outer_id,is_virtual,is_taobao,is_ex,is_timing,"
                + "is_3D,score,volume,one_station,second_kill,auto_fill,props_name,"
                + "violation,created,is_prepay,ww_status,promoted_service,prop_img,"
                + "item_img,sku,location,food_security,locality_life,desc_module_info,barcode," + "with_hold_quantity");
        req.setNumIids(strNumiid);
        ItemsSellerListGetResponse rsp = client.execute(req, shopVO.getSessionKey());
        // 记录日志
        logUtil.info(new DBLog(strNumiid, "top_api", "taobao.items.seller.list.get", rsp.getBody()));

        if (!rsp.isSuccess()) {
            return 0;
        }
        if (rsp.getItems() == null || rsp.getItems().size() < 1) {
            return 1;
        }

        for (com.taobao.api.domain.Item item : rsp.getItems()) {

            // 获取商品数据
            TopItem topItem = new TopItem();
            BeanUtils.copyProperties(topItem, item);

            // 检查商品是否存在
            int tempItem = 0;
            TopItem topItemModel = (TopItem) dao.find("selectByItemIdTopItem", item.getNumIid().toString());
            if (topItemModel == null) {
                // 添加TopItem数据
                topItem.setTopItemId(SnoGerUtil.getUUID());
                tempItem = dao.insert("insertSelectiveTopItem", topItem);
            } else {
                // 更新TopItem数据
                topItem.setTopItemId(topItemModel.getTopItemId());
                tempItem = dao.update("updateByPrimaryKeySelectiveTopItem", topItem);
            }

            // 执行成功
            if (tempItem > 0) {
                // SKU标记为删除
                dao.update("deleteByNumIidTopSku", item.getNumIid());
                // 添加TopSku数据
                if (item.getSkus() != null && item.getSkus().size() > 0) {
                    for (com.taobao.api.domain.Sku sku : item.getSkus()) {

                        TopSku topSku = new TopSku();
                        BeanUtils.copyProperties(topSku, sku);

                        // 检查Sku是否存在
                        Map<String, Object> reqParamSku = new HashMap<String, Object>();
                        reqParamSku.put("numIid", item.getNumIid());
                        reqParamSku.put("skuId", sku.getSkuId());
                        TopSku topSkuModel = (TopSku) dao.find("selectByNumIidAndSkuIdTopSku", reqParamSku);
                        if (topSkuModel == null) {
                            // 插入
                            topSku.setTopSkuId(SnoGerUtil.getUUID());
                            topSku.setTopItemId(topItem.getTopItemId());
                            topSku.setNumIid(item.getNumIid());
                            if (dao.insert("insertSelectiveTopSku", topSku) > 0) {
                                topItem.getTopSkuList().add(topSku);
                            }
                        } else {
                            // 更新
                            topSku.setTopSkuId(topSkuModel.getTopSkuId());
                            topSku.setTopItemId(topItem.getTopItemId());
                            topSku.setNumIid(item.getNumIid());
                            topSku.setDeleted("n");
                            if (dao.update("updateByNumIidAndSkuIdSelectiveTopSku", topSku) > 0) {
                                topItem.getTopSkuList().add(topSku);
                            }
                        }
                    }
                }
            }

            if (tempItem > 0) {
                topItemList.add(topItem);
            }
        }
        return 1;
    }

    /**
     * 自动同步店铺库存并上下架
     *
     * @param shopId
     * @return 错误消息
     * @throws Exception 异常
     */
    @Override
    public String autoSynchStock(String shopId) throws Exception {
        String allErrMsg = "";
        ItemVO searchItemVO = new ItemVO();
        searchItemVO.setShopId(shopId);
        List<ItemVO> itemDataList = itemDAO.selectDataForSynchStock(searchItemVO);

        if (itemDataList.size() > 0) {
            // 平台商品列表
            for (ItemVO itemData : itemDataList) {
                String errMsg = "";
                long sumStorage = 0; // 库存数合计
                ItemVO searchItemSkuVO = new ItemVO();
                searchItemSkuVO.setShopId(shopId);
                searchItemSkuVO.setEcItemId(itemData.getEcItemId());
                List<ItemVO> itemSkuList = itemDAO.selectSkuForSynchStock(searchItemSkuVO);
                String autoList = itemData.getAutoList();

                // 平台商品SKU列表
                for (ItemVO itemSku : itemSkuList) {
                    Map<String, Object> resultMap = this.synchStock(itemSku);
                    String msg = (String) resultMap.get("msg");
                    if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
                        return msg;
                    }
                    errMsg = errMsg + resultMap.get("msg");
                    sumStorage = sumStorage + Long.parseLong(resultMap.get("storage").toString());
                }

                if ("".equals(errMsg)) {
                    // 平台商品上下架
                    if (sumStorage <= 0) { // 下架
                        errMsg = errMsg + listDelist(itemData, false, 0);
                    } else if ("y".equals(autoList) && sumStorage > 0) { // 上架
                        errMsg = errMsg + listDelist(itemData, true, sumStorage);
                    }
                }

                allErrMsg = allErrMsg + errMsg;
            }
        } else {
            allErrMsg = "没有满足同步库存条件(店铺是否允许库存同步,平台商品是否允许库存同步,平台商品是否关联系统商品)";
        }

        return allErrMsg;
    }

    /**
     * 手动同步库存根据商品
     *
     * @param ecItemId
     * @return 错误消息
     * @throws Exception 异常
     */
    @Override
    public String manualSynchStockByItem(String ecItemId) throws Exception {
        String allErrMsg = "";
        ItemVO searchItemVO = new ItemVO();
        searchItemVO.setEcItemId(ecItemId);
        List<ItemVO> itemDataList = itemDAO.selectDataForSynchStock(searchItemVO);

        if (itemDataList.size() > 0) {
            // 平台商品列表
            for (ItemVO itemData : itemDataList) {
                String errMsg = "";
                long sumStorage = 0; // 库存数合计
                ItemVO searchItemSkuVO = new ItemVO();
                searchItemSkuVO.setShopId(itemData.getShopId());
                searchItemSkuVO.setEcItemId(itemData.getEcItemId());
                List<ItemVO> itemSkuList = itemDAO.selectSkuForSynchStock(searchItemSkuVO);

                // 平台商品SKU列表
                for (ItemVO itemSku : itemSkuList) {
                    Map<String, Object> resultMap = this.synchStock(itemSku);
                    String msg = (String) resultMap.get("msg");
                    if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
                        return msg;
                    }
                    errMsg = errMsg + resultMap.get("msg");
                    sumStorage = sumStorage + Long.parseLong(resultMap.get("storage").toString());
                }

                if ("".equals(errMsg)) {
                    // 平台商品上下架
                    if (sumStorage <= 0) { // 下架
                        errMsg = errMsg + listDelist(itemData, false, sumStorage);
                    }
                }

                allErrMsg = allErrMsg + errMsg;
            }
        } else {
            ItemVO parameter = new ItemVO();
            parameter.setEcItemId(ecItemId);
            Item itemModel = (Item) dao.find("selectItemInfo", parameter);
            allErrMsg = "平台商品编码:" + itemModel.getEcItemCode() + "没有满足同步库存条件(店铺是否允许库存同步,平台商品是否允许库存同步,平台商品是否关联系统商品)\\n";
        }

        return allErrMsg;
    }

    /**
     * 手动同步库存根据SKU
     *
     * @param ecSkuId
     * @return 错误消息
     * @throws Exception 异常
     */
    @Override
    public String manualSynchStockBySku(String ecSkuId) throws Exception {
        // 按平台商品SKU同步库存
        String errMsg = "";
        ItemVO searchItemVO = new ItemVO();
        searchItemVO.setEcSkuId(ecSkuId);
        List<ItemVO> itemSkuList = itemDAO.selectSkuForSynchStock(searchItemVO);

        if (itemSkuList.size() > 0) {
            // 平台商品SKU列表
            for (ItemVO itemSku : itemSkuList) {
                Map<String, Object> resultMap = this.synchStock(itemSku);
                String msg = (String) resultMap.get("msg");
                if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
                    return msg;
                }
                errMsg = errMsg + resultMap.get("msg");
            }
        } else {
            errMsg = "没有满足同步库存条件(店铺是否允许库存同步,平台商品是否允许库存同步,平台商品是否关联系统商品)";
        }

        return errMsg;
    }

    /**
     * 商品上下架
     *
     * @param itemData   平台商品VO
     * @param listFlg    上架FLG(true:上架,false:下架)
     * @param sumStorage 商品库存数
     * @return 错误消息
     * @throws Exception 异常
     */
    @SuppressWarnings("unchecked")
    private String listDelist(ItemVO itemData, boolean listFlg, long sumStorage) throws Exception {
        String errMsg = "";
        String ecItemCode = itemData.getEcItemCode();

        String url = omsUrl;
        String requestParams = "";
        Item item = new Item();
        if (listFlg) { // 上架
            url = url + "pushItem/pushItemListing.action";
            PushItemListing pushItemListing = new PushItemListing();
            pushItemListing.setShopId(itemData.getShopId());
            pushItemListing.setEcItemCode(ecItemCode);
            pushItemListing.setStockCount(String.valueOf(sumStorage));
            requestParams = JSON.toJSONString(pushItemListing);
            item.setEcItemCode(ecItemCode);
            item.setApproveStatus("上架");
            item.setListTime(new Date());
        } else { // 下架
            url = url + "pushItem/pushItemDeListing.action";
            PushItemDeListing pushItemDeListing = new PushItemDeListing();
            pushItemDeListing.setShopId(itemData.getShopId());
            pushItemDeListing.setEcItemCode(ecItemCode);
            requestParams = JSON.toJSONString(pushItemDeListing);
            item.setEcItemCode(ecItemCode);
            item.setApproveStatus("下架");
            item.setDelistTime(new Date());
        }
        String resJson = HttpUtils.sendByPostJson(url, requestParams);
        Map<String, Object> resultMap = JSON.parseObject(resJson, Map.class);
        if ("y".equals(resultMap.get("success"))) {
            itemDAO.update(item);
        } else {
            logUtil.info(new DBLog(ecItemCode, "", "synchStock",
                    DateUtil.getCurrentDateStr() + " 同步库存平台商品编码为【" + ecItemCode + "】同步失败," + resultMap.get("msg")));
            errMsg = errMsg + "平台商品编码:" + ecItemCode + resultMap.get("msg") + "\\n";
            // TODO 发邮件
        }

        return errMsg;
    }

    /**
     * 计算库存数
     *
     * @param itemVO 平台商品VO
     * @return 计算结果
     * @throws Exception 异常
     */
    private JSONObject caculateStock(ItemVO itemVO) throws Exception {
        String requestStr = StringUtil.format("stockPush/caculateStock.action?projectId=%s&shopIds=%s&skuIds=%s", itemVO.getPrjId(),
                itemVO.getShopId(), itemVO.getSkuId());
        String requestUrl = omsUrl + requestStr;
        String resJson = HttpUtils.sendByGet(requestUrl, null);
        JSONObject jsonObject = JSON.parseObject(resJson, JSONObject.class);

        return jsonObject;
    }

    /**
     * 同步店铺库存并上下架
     *
     * @param itemSku
     * @return 错误消息
     * @throws Exception 异常
     */
    @SuppressWarnings("unchecked")
    private Map<String, Object> synchStock(ItemVO itemSku) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        String returnMsg = "";
        long storage = 0; // 库存数

        // 计算系统商品库存数
        if ("n".equals(itemSku.getIsGroup())) { // 非组合商品
            JSONObject jsonObject = caculateStock(itemSku);
            if ("success".equals(jsonObject.get("result"))) {
                storage = Integer.parseInt(jsonObject.get("storage").toString());
            } else {
                String msg = (String) jsonObject.get("msg");
                logUtil.info(new DBLog(itemSku.getEcSkuCode(), "", "synchStock",
                        DateUtil.getCurrentDateStr() + " 平台规格编码为【" + itemSku.getEcSkuCode() + "】同步失败," + msg));
                if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
                    returnMap.put("msg", msg);
                    returnMap.put("storage", 0);
                    return returnMap;
                }
                returnMsg = returnMsg + "平台规格编码:" + itemSku.getEcSkuCode() + msg + "\\n";
            }
        } else { // 组合商品
            ItemVO searchItemVO = new ItemVO();
            searchItemVO.setEcSkuId(itemSku.getEcSkuId());
            List<ItemVO> groupSkuList = itemDAO.selectSkuForGroup(searchItemVO);

            for (int i = 0; i < groupSkuList.size(); i++) {
                ItemVO groupSku = groupSkuList.get(i);
                groupSku.setPrjId(itemSku.getPrjId());
                groupSku.setShopId(itemSku.getShopId());
                JSONObject jsonObject = caculateStock(groupSku);
                if ("success".equals(jsonObject.get("result"))) {
                    long tempStorage = Integer.parseInt(jsonObject.get("storage").toString());
                    double upRate = Float.parseFloat(groupSku.getUpRate());
                    long num = Integer.parseInt(groupSku.getNum());
                    // 库存 = 库存数 * 推送系数 / 数量 向下取整
                    tempStorage = (long) Math.floor(tempStorage * upRate / num);

                    // 取最小值
                    if (i == 0) {
                        storage = tempStorage;
                    } else {
                        if (tempStorage < storage) {
                            storage = tempStorage;
                        }
                    }
                } else {
                    String msg = (String) jsonObject.get("msg");
                    logUtil.info(new DBLog(itemSku.getEcSkuCode(), "", "synchStock",
                            DateUtil.getCurrentDateStr() + " 平台规格编码为【" + itemSku.getEcSkuCode() + "】同步失败," + msg));
                    if ("该店铺未配置可推送仓库".equals(msg) || "该店铺未设置仓库推送比例".equals(msg)) {
                        returnMap.put("msg", msg);
                        returnMap.put("storage", 0);
                        return returnMap;
                    }
                    returnMsg = returnMsg + "平台规格编码:" + itemSku.getEcSkuCode() + msg + "\\n";
                    break;
                }
            }
        }

        if ("".equals(returnMsg)) {
            // 库存同步
            PushItemQuantityUpdate pushItemQuantityUpdate = new PushItemQuantityUpdate();
            pushItemQuantityUpdate.setShopId(itemSku.getShopId());
            pushItemQuantityUpdate.setEcItemCode(itemSku.getEcItemCode());
            String ecSkuCode = itemSku.getEcSkuCode();
            if (ecSkuCode != null && "0".equals(ecSkuCode)) {
                ecSkuCode = null;
            }
            pushItemQuantityUpdate.setSkuId(ecSkuCode);
            pushItemQuantityUpdate.setNum(String.valueOf(storage));
            String requestParams = JSON.toJSONString(pushItemQuantityUpdate);
            String resJson = HttpUtils.sendByPostJson(omsUrl + "pushItem/pushItemQuantityUpdate.action", requestParams);
            Map<String, Object> resultMap = JSON.parseObject(resJson, Map.class);
            if ("n".equals(resultMap.get("success"))) {
                logUtil.info(new DBLog(itemSku.getEcSkuCode(), "", "synchStock",
                        DateUtil.getCurrentDateStr() + " 【" + itemSku.getEcSkuCode() + "】同步失败," + resultMap.get("msg")));
                returnMsg = returnMsg + "平台规格编码:" + itemSku.getEcSkuCode() + resultMap.get("msg") + "\\n";
                // TODO 发邮件
            }
        }

        returnMap.put("msg", returnMsg);
        returnMap.put("storage", storage);
        return returnMap;
    }

}
